
var Nav = function() {
  this.init()
}

Nav.prototype.init = function () {
  this.getElements().bindEvents(this).getNavItems(this)
}

Nav.prototype.getElements = function () {
  this.$body = $(document.body)
  this.$bar = this.$body.find('.bar')
  this.$navBar = this.$bar.find('.bar-nav')
  this.$barAside = this.$bar.find('.bar-aside')
  this.iframe = this.$id('iframe')
  return this
}

Nav.prototype.getNavItems = function(nav) {
  // /menu/getMenuList.htm
  $.getJSON('/assets/javascripts/nav.json').done(function(data) {
    if (data && data.resultData && data.resultData.length) {
      var navHtml = template('nav-template', data)
      var barAside = template('bar-aside-template', data)
      nav.$navBar.html(navHtml)
      nav.$barAside.html(barAside)
    }
  })
}

Nav.prototype.bindEvents = function (nav) {
  this.$navBar.on('click', '.bar-li > a', function() {
    var $li = $(this.parentNode)
    var $subNav = $li.find('.bar-subnav')
    if ($subNav.length) {
      if ($li.hasClass('active')) {
        $li.removeClass('active').find('.bar-subnav').stop(true).slideUp(300)
      } else {
        $li.addClass('active').find('.bar-subnav').stop(true).slideDown(300)
        $li.siblings().removeClass('active').find('.bar-subnav').stop(true).slideUp(300)
      }
    } else {
      nav.iframe.src = this.href
      return false
    }
  }).on('mouseenter', '.bar-sub-li', function (e) {
    e.stopPropagation()
    $(this).addClass('active').siblings().removeClass('active')
  }).on('mouseenter', 'a', function(e) {
    var href = this.getAttribute('href')
    var target = href[0] === '#' ? $(href) : ''
    if (target.length) {
      e.preventDefault()
      if (nav.lastClickedSideBar === this) {
        nav.hideBarAside()
      } else {
        nav.showBarAside(this)
      }
      target.show().siblings().hide()
    } else {
      nav.hideBarAside()
    }
  }).on('click', '.bar-subnav a', function(e) {
    var href = this.getAttribute('href')
    var target = href[0] === '#' ? $(href) : ''
    if (!target.length) {
      nav.iframe.src = this.href
    }
    return false
  })

  this.$barAside.on('click', '.bar-close', function() {
    nav.hideBarAside()
  }).on('click', 'li a', function(e) {
    e.preventDefault()
    nav.iframe.src = this.href
  })
  return this
}

Nav.prototype.hideBarAside = function() {
  this.$bar.removeClass('active')
  this.lastClickedSideBar = null
}

Nav.prototype.showBarAside = function(target) {
  this.$bar.addClass('active')
  this.lastClickedSideBar = target
}

Nav.prototype.$id = function(id) {
  return document.getElementById(id)
}

module.exports = Nav
